﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace OnlineSoccerManager
{
    
    public class HttpRequest
    {

        private CookieContainer cookies = new CookieContainer();
        private Encoding pageEncoding = Encoding.GetEncoding("iso-8859-1");
        private string urlBase = "";

        public HttpRequest()
        {
        }

        public HttpRequest(string baseUrl)
        {
            this.UrlBase = baseUrl;
        }




        public Encoding PageEncoding
        {
            get
            {
                return this.pageEncoding;
            }
            set
            {
                this.pageEncoding = value;
            }
        }

        public string UrlBase
        {
            get
            {
                return this.urlBase;
            }
            set
            {
                this.urlBase = value;

                if (this.urlBase == null)
                    this.urlBase = "";

                if (this.urlBase != "" && this.urlBase.Last() != '/')
                    this.urlBase += "/";
            }
        }



        public string PostFormular(string page, Dictionary<string, string> post)
        {

            string document = null;
            string postData = String.Join("&", post.Select(e => String.Format("{0}={1}", e.Key, e.Value)));
            using (Stream responseStream = this.PostStream(page, postData, "application/x-www-form-urlencoded"))
            {
                if (responseStream == null)
                    return null;

                TextReader reader = new StreamReader(responseStream, this.pageEncoding);
                document = reader.ReadToEnd();
                responseStream.Close();
                reader.Close();
            }

            return document;
        }

        public Stream PostStream(string page, string postdata, string contentType)
        {
            try
            {

                // get binary data to write to stream
                byte[] data = pageEncoding.GetBytes(postdata);
                // create request
                HttpWebRequest request = HttpWebRequest.CreateHttp(this.urlBase + page);
                // use post as method
                request.Method = "POST";
                request.MaximumAutomaticRedirections = 1;
                request.ContentType = contentType;
                request.CookieContainer = this.cookies;
                request.UserAgent = "OnlineSoccerManager Alpha Version 0.1";

                // write binary data to request
                request.ContentLength = data.Length;
                using (Stream requestStream = request.GetRequestStream())
                {
                    requestStream.Write(data, 0, data.Length);
                    requestStream.Close();
                }

                // wait for response
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;

                // check if response is ok... otherwise return null
                if (response.StatusCode != HttpStatusCode.OK)
                    return null;


                // return reponse stream
                return response.GetResponseStream();

            }
            catch (Exception e)
            {
                return null;
            }
        }

        public Bitmap GetImage(string page)
        {
            string contentType = GetMimeType(page);
            Bitmap image = null;
            using (Stream responseStream = this.GetStream(page, null, contentType))
            {
                if (responseStream == null)
                    return null;

                image = Bitmap.FromStream(responseStream) as Bitmap;
                responseStream.Close();
            }
            return image;
            
        }


        public string GetPage(string page, Dictionary<string, string> get)
        {
            string document = null;
            string getData = String.Join("&", get.Select(e => String.Format("{0}={1}", e.Key, e.Value)));
            using (Stream responseStream = this.GetStream(page, getData, "text/html"))
            {
                if (responseStream == null)
                    return null;
                TextReader reader = new StreamReader(responseStream, this.pageEncoding);
                document = reader.ReadToEnd();
                responseStream.Close();
                reader.Close();
            }
            return document;
        }

        public Stream GetStream(string page, string getdata, string contentType)
        {
            try 
            {
                // create request
                HttpWebRequest request = HttpWebRequest.CreateHttp(this.urlBase + page + (String.IsNullOrEmpty(getdata)? "" : "?" + getdata));
                // use post as method
                request.Method = "GET";
                request.MaximumAutomaticRedirections = 1;
                request.MediaType = "HTTP/1.1";
                request.ContentType = contentType;
                request.CookieContainer = this.cookies;
                request.UserAgent = "OnlineSoccerManager Alpha Version 0.1";

                // wait for response
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;

                // check if response is ok... otherwise return null
                if (response.StatusCode != HttpStatusCode.OK)
                    return null;

                // return stream
                return response.GetResponseStream();
            }
            catch (Exception e)
            {
                return null;
            }
        }

        private string GetMimeType(string page) {
            string extension = Path.GetExtension(page);

            if (extension.Contains("."))
                extension = extension.Replace(".", "");

            switch (extension.ToLower()) {
                case "png":
                    return "image/png";
                case "gif":
                    return "image/gif";
                case "jpg":
                case "jpeg":
                default:
                    return "image/jpeg";
            }
        }
    }
}
